<html>
	<head>
		<title>IoT City Test Portal</title>
		<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
		<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  
		<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
		<script src="https://code.highcharts.com/stock/highstock.js"></script>
		<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>

		<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
		<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  
		<script src="{{ url_for("static", filename="ws.js") }}"></script>
		
		<link href='http://fonts.googleapis.com/css?family=PT+Sans:400,700,400italic' rel='stylesheet' type='text/css'>
		<link href='{{ url_for("static", filename="style.css") }}' rel='stylesheet' type='text/css'>
	</head>
	<body>
		<script type="text/javascript">
            var service_url="http://localhost:8000/authenticated";
            var token=localStorage.getItem('access_token');

            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4) {
                    if (xhr.status != 200) {
                        window.location.replace("/login");
                        return false;
                    }
                    return true;
                }
            }
            xhr.open("GET", service_url, true);
            xhr.setRequestHeader('Authorization', 'Bearer ' + token);
            xhr.send();
        </script>

		<div class="sidenav">
			<a href="/">Home</a>
			<a href="/verticals">Verticals</a>
			<a href="/devices">Devices</a>
			<a href="/subscriptions">Subscriptions</a>
            <a href="/alerts">Alerts</a>
            <a href="/triggered">Triggered</a>
		</div>

		<div body style="margin-left: 200px;">
			<table id="devices">
				<tr>
					<td>Name</td>
					<td>ID</td>
					<td>Secret</td>
					<td>Vertical</td>
					<td>Description</td>
					<td>Location</td>
					<td>Streams</td>
					<td>Delete</td>
				</tr>
			</table>


			<button id="create-user">Create new device</button>
		
			<div id="dialog-form" title="Add Device">
		 
			  <form>
				<fieldset>
				  <label for="name">Name</label>
				  <input type="text" name="name" id="name" value="" class="text ui-widget-content ui-corner-all">
				  <label for="vertical">Vertical</label>
				  <input type="text" name="vertical" id="vertical" value="" class="text ui-widget-content ui-corner-all">
				  <label for="location">Location</label>
				  <input type="text" name="location" id="location" value="" class="text ui-widget-content ui-corner-all">
				  <label for="description">Description</label>
				  <input type="text" name="description" id="description" value="" class="text ui-widget-content ui-corner-all">
			 
				  <!-- Allow form submission with keyboard without duplicating the dialog button -->
				  <input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
				</fieldset>
			  </form>
			</div>
		</div>
		<script type="text/javascript">

			$( function() {
				var dialog, form,
			 
				name = $( "#name" ),
				email = $( "#vertical" ),
				location = $( "#location" ),
				description = $ ( "#description" );
			 
			 
				function addDevice() {

					var xhr = new XMLHttpRequest();
					data = {"name": document.getElementById("name").value, "vertical": document.getElementById("vertical").value, "location": document.getElementById("location").value, "description": document.getElementById("description").value};
					xhr.open("POST", service_url+"/device", true);
					xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
					xhr.setRequestHeader('ACCOUNT-ID', 'ua1');
					xhr.setRequestHeader('ACCOUNT-SECRET', '8ik8fm0h8mqer821agae3qg29ve1kl84d9b0svsiesqj52lil59g');
					xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('access_token'));
					xhr.send(JSON.stringify(data));
					xhr.onloadend = function () {
						window.location.reload();
					};

				}
			 
				dialog = $( "#dialog-form" ).dialog({
					autoOpen: false,
					height: 400,
					width: 350,
					modal: true,
					buttons: {
						"Add Device": addDevice,
						Cancel: function() {
							dialog.dialog( "close" );
						}
					},
					close: function() {
					form[ 0 ].reset();
				 	}
				});
			 
				form = dialog.find( "form" ).on( "submit", function( event ) {
					event.preventDefault();
					addDevice();
				});
			 
				$( "#create-user" ).button().on( "click", function() {
					dialog.dialog( "open" );
				});
			});

			var service_url="http://localhost:8000";
			var url = service_url+'/device';
			$.ajax({ url: url,
				headers: {'Authorization': 'Bearer ' + localStorage.getItem('access_token')},
				success: function(data) {
					values = data["values"];

					for(value in values){
						var table = document.getElementById("devices");
						var row = table.insertRow(-1);
						var cell1 = row.insertCell(0);
						var cell2 = row.insertCell(1);
						var cell3 = row.insertCell(2);
						var cell4 = row.insertCell(3);
						var cell5 = row.insertCell(4);
						var cell6 = row.insertCell(5);
						var cell7 = row.insertCell(6);
						var cell8 = row.insertCell(7);
						
						var button = document.createElement("button");
						(function(id){
							button.addEventListener('click', function(){ deleteDevice(id); }, true);
						})(values[value]["id"]);
						button.innerHTML = "Delete";

						var button2 = document.createElement("button");
						(function(id){
							button2.addEventListener('click', function(){ window.location.href="/device/"+id+"/streams" }, true);
						})(values[value]["id"]);
						button2.innerHTML = "See streams";
						
						cell1.innerHTML = values[value]["name"];
						cell5.innerHTML = values[value]["description"];
						cell2.innerHTML = values[value]["id"];
						cell3.innerHTML = values[value]["secret"];
						cell6.innerHTML = values[value]["location"];
						cell4.innerHTML = values[value]["vertical"];
						cell8.appendChild(button);
						cell7.appendChild(button2);
					}
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
				}
			});

			function deleteDevice(id){
                var xhr = new XMLHttpRequest();
                xhr.open("DELETE", service_url+"/device/"+id, true);
                xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
                xhr.setRequestHeader('ACCOUNT-ID', 'ua1');
				xhr.setRequestHeader('ACCOUNT-SECRET', '8ik8fm0h8mqer821agae3qg29ve1kl84d9b0svsiesqj52lil59g')
				xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('access_token'));
                xhr.send();
                xhr.onloadend = function () {
                    location.reload();
                };
            }

		</script>
	</body>
</html>

